import {
  AppstoreOutlined,
  BarsOutlined,
  CaretDownOutlined,
  EditFilled,
  PlusOutlined,
} from "@ant-design/icons";
import { Button, Col, Dropdown, Row, Select, Tabs } from "antd";
import { useEffect, useRef, useState } from "react";
import { gutter } from "../const/keys";
import styles from "./index.modules.less";
import AddModal from "./AddModal";
import { types } from "./const";
import { useUser } from "@/hooks/useUser";
import { ProTable } from "@ant-design/pro-components";
import { Link } from "@umijs/max";
import {
  deleteSale,
  getMySaleList,
  getRelatedSaleList,
  getSaleList,
} from "@/services/sale";
import PopconfirmButton from "@/components/PopconfirmButton";
import SaleCard from "./SaleCard";
import { TabsType } from "./type";
import { formatData } from "@/utils";
import { useAccess } from "@/hooks/access";
import { getCustomerList } from "@/services/customer";
import { debounce } from "lodash";

const App = () => {
  const myTable = useRef<any>(null);
  const { permissions } = useAccess();
  const showAll = permissions.includes("ying:opportunity:listall");
  const [activeKey, setActiveKey] = useState<TabsType>(showAll ? "ALL" : "MY");
  const [params, setParams] = useState<any>({});
  const [viewMode, setViewMode] = useState<string>(
    localStorage.getItem("saleViewMode") || "card"
  );
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [id, setId] = useState<number>();
  const [addOpen, setAddOpen] = useState<boolean>(false);
  const { userOptions } = useUser();
  const [options, setOptions] = useState<any[]>([]);
  const getCustomerData = async (searchValue: string) => {
    const { data } = await getCustomerList({
      pageNum: 1,
      pageSize: 10,
      searchValue,
    });
    setOptions(
      data?.map((item: { customerName: any; id: any }) => {
        return { label: item.customerName, value: item.id };
      }) || []
    );
  };
  const columns = [
    {
      title: "名称",
      dataIndex: "opportunityName",
      render: (_: any, record: any) => (
        <Link to={`/sale/detail/${record.id}`}>{record.opportunityName}</Link>
      ),
    },
    {
      title: "业主",
      dataIndex: "searchCustomerId",
      key: "searchCustomerId",
      valueType: "select",

      // fieldProps: {
      //   placeholder: "请输入客户名称搜索",
      //   showSearch: true,
      //   filterOption: false,
      //   onSearch: (value: string) => {
      //     getCustomerData(value);
      //   },
      //   options,
      // },
      renderFormItem: () => {
        return (
          <Select
            showSearch
            allowClear
            filterOption={false}
            placeholder="请输入业主名称搜索"
            options={options}
            onClear={() => {
              getCustomerData("");
            }}
            onSearch={(value) => {
              getCustomerData(value);
            }}
          />
        );
      },
      render: (_: any, record: any) => {
        return formatData(record.firstCustomerName);
      },
    },
    {
      title: "负责人",
      dataIndex: "projectLeaderUserId",
      key: "projectLeaderUserId",
      valueType: "select",
      fieldProps: {
        options: userOptions,
      },
      render: (_: any, record: any) => {
        return formatData(record.projectLeaderUserName);
      },
    },
    //项目阶段
    {
      title: "项目阶段",
      dataIndex: "projectStage",
      search: false,
      render: (_: any, record: any) => {
        const type = types.find((item) => item.value === record.projectStage);
        return type ? type.label : "-";
      },
    },
    //transactionProbability
    {
      title: "成单概率",
      dataIndex: "transactionProbability",
      search: false,
      render: (_: any, record: any) => {
        return `${record.transactionProbability}%`;
      },
    },
    //预估合同额
    {
      title: "预估合同额",
      dataIndex: "estimatedContractAmount",
      search: false,
      render: (_: any, record: any) => {
        return `${(record.estimatedContractAmount / 100).toFixed(2)}`;
      },
    },
    {
      title: "最后跟进人",
      dataIndex: "lastFollowMemberId",
      key: "lastFollowMemberId",
      valueType: "select",
      fieldProps: {
        options: userOptions,
      },
    },
    //最后跟进时间
    {
      title: "最后跟进时间",
      dataIndex: "lastFollowTime",
      search: false,
    },
    //操作
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      render: (_: any, record: any) => [
        <Button
          size="small"
          type="link"
          icon={<EditFilled />}
          key="edit"
          onClick={() => {
            setId(record.id);
            setAddOpen(true);
          }}
        >
          编辑
        </Button>,
        <PopconfirmButton
          size="small"
          type="link"
          key={"del"}
          onConfirm={async () => {
            const { success } = await deleteSale(record.id);
            if (success) {
              setPageNum(1);
              myTable.current?.reload();
            }
          }}
        >
          删除
        </PopconfirmButton>,
      ],
    },
  ];
  useEffect(() => {
    getCustomerData("");
  }, []);
  useEffect(() => {
    localStorage.setItem("saleViewMode", viewMode);
  }, [viewMode]);
  return (
    <div className={styles.wrap}>
      <Tabs
        activeKey={activeKey}
        onChange={(activeKey) => {
          setActiveKey(activeKey as TabsType);
        }}
        //右边
        tabBarExtraContent={
          <Row gutter={[gutter, gutter]}>
            <Col>
              <Button
                ghost
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => {
                  setId(undefined);
                  setAddOpen(true);
                }}
              >
                新建商机
              </Button>
            </Col>

            <Col>
              <Dropdown
                menu={{
                  items: [
                    {
                      key: "grid",
                      label: (
                        <span
                          style={{
                            cursor: viewMode === "grid" ? "default" : "pointer",
                            color: viewMode === "grid" ? "gray" : undefined,
                          }}
                        >
                          <BarsOutlined />
                          &nbsp; 列表视图
                        </span>
                      ),
                      onClick: () => setViewMode("grid"),
                    },
                    {
                      key: "card",
                      label: (
                        <span
                          style={{
                            cursor: viewMode === "card" ? "default" : "pointer",
                            color: viewMode === "card" ? "gray" : undefined,
                          }}
                        >
                          <AppstoreOutlined />
                          &nbsp; 看板视图
                        </span>
                      ),
                      onClick: () => setViewMode("card"),
                    },
                  ],
                }}
              >
                <Button
                  icon={
                    viewMode === "grid" ? (
                      <BarsOutlined />
                    ) : (
                      <AppstoreOutlined />
                    )
                  }
                >
                  {viewMode === "grid" ? "列表" : "看板"}视图
                  <CaretDownOutlined />
                </Button>
              </Dropdown>
            </Col>
          </Row>
        }
        items={[
          showAll
            ? {
                label: "全部商机",
                key: "ALL",
                children: <></>,
              }
            : undefined,
          {
            label: "我负责的",
            key: "MY",
            children: <></>,
          },
          {
            label: "与我有关",
            key: "FOLLOW",
            children: <></>,
          },
        ].filter((item) => item !== undefined)}
      />
      <ProTable
        actionRef={myTable}
        columns={columns}
        scroll={{
          x: 1000,
        }}
        search={{
          defaultCollapsed: false,
        }}
        params={{
          activeKey,
        }}
        request={async (params) => {
          setParams(params);
          const submitData = { ...params, pageNum, pageSize };
          const { rows, total, success } =
            activeKey === "ALL"
              ? await getSaleList(submitData)
              : activeKey === "MY"
              ? await getMySaleList(submitData)
              : await getRelatedSaleList(submitData);
          return { data: rows, total, success };
        }}
        pagination={{
          pageSize,
          current: pageNum,
          onChange: (page, size) => {
            setPageNum(page);
            setPageSize(size || 10);
          },
        }}
        tableRender={
          viewMode === "card"
            ? () => (
                <SaleCard
                  key={JSON.stringify(params)}
                  tabsKey={activeKey as TabsType}
                  params={params}
                />
              )
            : undefined
        }
      />

      {addOpen ? (
        <AddModal
          id={id}
          onClose={() => setAddOpen(false)}
          onOk={() => {
            setAddOpen(false);
            setId(undefined);
            myTable.current?.reload();
          }}
        />
      ) : null}
    </div>
  );
};
export default App;
